<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getDefault } from '@/api/address'
import { getConfig } from '@/api/config'
import { upload } from '@/api/file'
import { publish } from '@/api/express'
import type { ExpressTake, ExpressTakeDetail } from '@/api/express/type'
import type { Address } from '@/api/address/type'
import type { BaseResponse } from '@/api/base'
import type { ExpressType } from '@/api/config/type'
import { toast } from '@/utils/common'
import { deliveryTime, sexLimit, reqExpressType } from './common'
import { baseUrl } from '@/config'

const expressFormRef = ref()
const deliveryTimeRef = ref()
const sexLimitRef = ref()
const expressStationRef = ref()
const address = ref<Address>()
const expressForm = ref<ExpressTake>({
	deliveryTime: 4,
	deliveryTimeName: '尽快送达',
	sexLimit: 0,
	sexLimitName: '不限制性别',
	bounty: 0,
	remark: null,
	price: 0,
	address: address.value
})
const expressDetailList = reactive<ExpressTakeDetail[]>([])
const expressDetailIndex = ref<number>()
const padPrice = ref(false)
const expressType = ref<ExpressType[]>([])
const expressTypePrice = ref({})
const deliveryTimeActions = ref(deliveryTime)
const sexLimitActions = ref(sexLimit)
const expressStationActions = ref([])

const rules = ref({
	deliveryTime: [
		{ required: true, message: '请选择期望送达时间' }
	],
	sexLimit: [
		{ required: true, message: '请选择性别限制' }
	]
})

const loadAddress = async () => {
	const res: BaseResponse = await getDefault()
	address.value = res.data
}
const loadExpressStation = async () => {
	const res: BaseResponse = await getConfig('EXPRESS_STATION')
	expressStationActions.value = res.data.map((item: any) => {
		return {
			name: item,
			value: item
		}
	})
}
const loadExpressType = async () => {
	const res: ExpressType[] = await reqExpressType()
	expressType.value = res
	expressTypePrice.value = res.reduce((pre: any, cur: any) => {
		pre[cur.type] = cur.price
		return pre
	}, {})
}

onLoad(async () => {
	await loadAddress()
	await loadExpressType()
	addDetail()
	loadExpressStation()
})

const showDeliveryTimeSelect = () => {
	deliveryTimeRef.value?.open();
	hideKeyboard();
}
const deliveryTimeSelect = (e: any) => {
	expressForm.value.deliveryTime = e.value
	expressForm.value.deliveryTimeName = e.name
}

const showSexLimitSelect = () => {
	sexLimitRef.value?.open();
	hideKeyboard();
}
const sexLimitSelect = (e: any) => {
	expressForm.value.sexLimit = e.value
	expressForm.value.sexLimitName = e.name
}

const disabledAddDetail = computed(() => {
	return expressDetailList.length >= 3
})

const addDetail = () => {
	const { type, price } = expressType.value[0]
	expressDetailList.push({
		type,
		price,
		expressStation: '',
		expressStationName: '',
		picture: '',
		pictureArr: [],
	})
}
const delDetail = (index: number) => {
	expressDetailList.splice(index, 1)
}

const showExpressStationSelect = (index: number) => {
	expressStationRef.value?.open();
	expressDetailIndex.value = index
	hideKeyboard();
}
const expressStationSelect = (e: any) => {
	expressDetailList[expressDetailIndex.value].expressStation = e.value
	expressDetailList[expressDetailIndex.value].expressStationName = e.name
}

const chooseType = (e: any, index: number) => {
	expressDetailList[index].price = expressTypePrice.value[e]
}

const afterRead = (e: any, index: number) => {
	try {
		let fileList = [].concat(e.file)
		const cur = expressDetailList[index]
		let fileListLen = cur.pictureArr.length
		fileList.map((item: any) => {
			cur.pictureArr.push({
				...item,
				status: 'uploading',
				message: '上传中'
			});
		})
		fileList.forEach(async (file: any) => {
			console.log(file)
			const res: BaseResponse = await upload(file.url, file.name)
			let item = cur.pictureArr[fileListLen];
			cur.pictureArr.splice(
				fileListLen,
				1,
				Object.assign(item, {
					status: 'success',
					message: '',
					url: res.data.actionUrl
				})
			)
			fileListLen++
		})
	} catch (e) {
		toast('上传失败')
	}
}

const deletePic = (e: any, index: number) => {
	expressDetailList[index].pictureArr.splice(e.index, 1)
}

const summaryPrice = computed(() => {
	let price = 0
	expressDetailList.forEach((item: ExpressTakeDetail) => {
		price += item.price
	})
	return price
})

const publishExpress = async () => {
	const res = await expressFormRef.value.validate()
	if (!res) {
		return
	}
	if (expressForm.value.deliveryTime === 5 && !expressForm.value.remark) {
		toast('请输入备注')
		return
	}
	if (!address.value) {
		toast('请添加收货地址')
		return
	}
	if (expressDetailList.length === 0) {
		toast('请添加快递')
		return
	}
	if (expressDetailList.some((item: ExpressTakeDetail) => {
		return !item.expressStation
	})) {
		toast('请选择驿站')
		return
	}
	if (expressDetailList.some((item: ExpressTakeDetail) => {
		return !item.takeCode
	})) {
		toast('请输入取件码')
		return
	}
	if (expressDetailList.some((item: ExpressTakeDetail) => {
		return item.pictureArr.length === 0
	})) {
		toast('请上传快递图片')
		return
	}
	expressForm.value.price = summaryPrice.value
	expressForm.value.address = address.value
	expressDetailList.forEach((item: ExpressTakeDetail) => {
		item.picture = item.pictureArr.map(item => item.url.substring(item.url.indexOf('files') - 1)).join(',')
	})
	expressForm.value.expressTakeDetails = expressDetailList
	try {
		const res: BaseResponse = await publish(expressForm.value)
		uni.navigateTo({ url: '/pages/pay/expressPay?orderNo=' + res.data })
	} catch (error) {
		toast(error.tips)
	}
}

const hideKeyboard = () => {
	uni.hideKeyboard()
}

const jumpAddress = () => {
	uni.navigateTo({
		url: '/pages/address/index?type=order',
		events: {
			sendAddress: function (data: Address) {
				address.value = data
			}
		}
	})
}
</script>

<template>
	<view class="express-create">
		<view class="address" v-if="address" @click="jumpAddress">
			<view class="address-icon">
				<uv-icon name="map-fill" color="#ff7700" size="45rpx"></uv-icon>
			</view>
			<view class="address-info">
				<view class="address-address">{{ address.building }} {{ address.address }}</view>
				<view class="address-name">{{ address.name }} {{ address.phone }}</view>
			</view>
			<uv-icon name="arrow-right" color="#ccc" size="28rpx"></uv-icon>
		</view>
		<view class="address" v-else>
			<uv-button type="primary" class="address-add" text="添加收货地址" @click="jumpAddress"></uv-button>
		</view>
		<view class="create-form">
			<uv-form labelPosition="left" :model="expressForm" :rules="rules" ref="expressFormRef" labelWidth="auto">
				<uv-form-item label="期望送达时间" prop="deliveryTime" borderBottom @click="showDeliveryTimeSelect">
					<uv-input v-model="expressForm.deliveryTimeName" disabled disabledColor="#ffffff" border="none"
						inputAlign="right" color="#999">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="性别限制" prop="sexLimit" borderBottom @click="showSexLimitSelect">
					<uv-input v-model="expressForm.sexLimitName" disabled disabledColor="#ffffff" border="none" inputAlign="right"
						color="#999">
					</uv-input>
					<template v-slot:right>
						<uv-icon name="arrow-right"></uv-icon>
					</template>
				</uv-form-item>
				<uv-form-item label="追加金额" borderBottom>
					<uv-switch v-model="padPrice" border="none" inputAlign="right"></uv-switch>
				</uv-form-item>
				<uv-form-item v-if="padPrice" label="金额" prop="bounty" borderBottom>
					<uv-input v-model="expressForm.bounty" type="number" border="none" maxlength="2" inputAlign="right"
						color="#999"></uv-input>
				</uv-form-item>
				<uv-form-item label="备注" prop="remark" borderBottom>
					<uv-input v-model="expressForm.remark" maxlength="200" border="none" placeholder="所有人可见" inputAlign="right"
						color="#999">
					</uv-input>
				</uv-form-item>
			</uv-form>
			<uv-button text="添加快递" :disabled="disabledAddDetail" @click="addDetail" shape="circle" color="#ff7744"
				:customStyle="{ width: '180rpx', height: '30px' }"></uv-button>
			<view class="create-form-detail-list">
				<view class="create-form-detail" v-for="(detail, index) in expressDetailList">
					<view v-if="index !== 0">
						<uv-icon name="close" @click="delDetail(index)"></uv-icon>
					</view>
					<view class="create-form-detail-item">
						<uv-text text="快递驿站"></uv-text>
						<uv-input v-model="detail.expressStation" required disabled disabledColor="#ffffff" border="none"
							inputAlign="right" color="#999" placeholder="请选择驿站" suffixIcon="arrow-right"
							@click="showExpressStationSelect(index)">
						</uv-input>
					</view>
					<uv-line></uv-line>
					<view class="create-form-detail-item" style="display: block;">
						<uv-text text="快递大小"></uv-text>
						<uv-radio-group v-model="detail.type" @change="chooseType($event, index)" style="justify-content: center;">
							<uv-radio :customStyle="{ margin: '8px' }" v-for="(item, i) in expressType" :key="i"
								:label="item.name + '￥' + item.price" :name="item.type" shape="square">
							</uv-radio>
						</uv-radio-group>
					</view>
					<uv-line></uv-line>
					<view class="create-form-detail-item">
						<uv-text text="取件码"></uv-text>
						<uv-input v-model="detail.takeCode" border="none" inputAlign="right" color="#999" placeholder="请输入取件码">
						</uv-input>
					</view>
					<uv-line></uv-line>
					<view class="create-form-detail-item" style="display: block;">
						<uv-text text="快递图片/短信截图"></uv-text>
						<uv-upload :fileList="detail.pictureArr" name="picture" multiple :maxCount="2" :previewFullImage="true"
							@afterRead="afterRead($event, index)" @delete="deletePic($event, index)"
							style="margin-top: 10rpx;"></uv-upload>
					</view>
				</view>
			</view>
		</view>
		<view class="create-bottom">
			<view class="create-bottom-price">
				需支付：
				<view>
					￥{{ summaryPrice }}
				</view>
				<view v-if="expressForm.bounty">
					+￥{{ expressForm.bounty }}
				</view>
			</view>
			<uv-button @click="publishExpress" text="立即发布" color="#ff7744"></uv-button>
		</view>
		<uv-action-sheet ref="deliveryTimeRef" :actions="deliveryTimeActions" title="请选择期望送达时间"
			@select="deliveryTimeSelect">
		</uv-action-sheet>
		<uv-action-sheet ref="sexLimitRef" :actions="sexLimitActions" title="请选择性别" @select="sexLimitSelect">
		</uv-action-sheet>
		<uv-action-sheet ref="expressStationRef" :actions="expressStationActions" title="请选择驿站"
			@select="expressStationSelect">
		</uv-action-sheet>
	</view>
</template>

<style lang="scss" scoped>
.address {
	background-color: #fff;
	border-radius: 10rpx;
	padding: 20rpx 20rpx;
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;

	.address-icon {
		margin-right: 10rpx;
	}

	.address-info {
		display: flex;
		flex-direction: column;
		width: calc(100% - 50rpx);

		.address-address {
			margin-bottom: 10rpx;
		}

		.address-name {
			color: #999;
		}
	}

	.address-add {
		width: 100%;
	}
}

.create-form {
	background-color: #fff;
	padding: 0 20rpx;

	::v-deep .uv-form {
		margin-bottom: 20rpx;

		.uv-form-item__body__right__content__slot {
			justify-content: flex-end;
		}
	}

	.create-form-detail-list {
		padding: 20rpx 0;

		.create-form-detail {
			padding: 20rpx 20rpx;
			border: 1px solid #eee;
			border-radius: 50rpx;
			margin-bottom: 10rpx;

			&-item {
				display: flex;
				padding: 10px 0;
			}
		}
	}
}

.create-bottom {
	position: fixed;
	bottom: 0;
	left: 0;
	width: calc(100% - 40rpx);
	background-color: #fff;
	padding: 20rpx;
	display: flex;
	justify-content: space-between;

	.create-bottom-price {
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #ff7744;
		font-weight: bold;
	}
}
</style>